<!DOCTYPE html> 
<!FB is defined from this address>
<html xmlns:fb="https://www.facebook.com/2008/fbml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
		<link rel="stylesheet" href="/styles.css" type="text/css" />
        <title>Facebook Test</title>
    </head>
    <body>
		<!Navigation and Content>
    	<div class="content">
    	<div class="nav_bar">
    		<ul>
				<li><a href='/'>Upload</a></li>
				<li class='currentPage'><a href='/facebook.html'>Facebook Pictures</a></li>
				<li><a href='/viewimages'>Saved Images</a></li>
				<li><a href='/viewpuzzles'>Saved Puzzles</a></li>
    		</ul>
    	</div><br /><br />
		<!END OF Navigation and Content>
		<!Facebook Root to be filled asynchronously. This includes the whole FB JavaScript API>
        <div id="fb-root"></div>
		<!Begining of the JavaScript that uses the Facebook API>
        <script type="text/javascript">
			// Facebook login button. Is being used to login/logout the user from Facebook
            var button;
			// UserInfo. Not absolutely needed, but a convenience at this point.
            var userInfo;
			// AccessToken. This is being used on calls to the Graph API
            var accessToken;
			// A flag from a legacy code, but still useful. Keeps track of whether a call to get images have been made
			var gotPhotos = false;
            window.fbAsyncInit = function() {
				// Application ID is hardcoded
                FB.init({ appId: '338030316264567', //change the appId to your appId
                    status: true, 
                    cookie: true,
                    xfbml: true,
                    oauth: true});

               showLoader(true);
               // Fills out the login/logout button, to be used if needed.
               function updateButton(response) {
                    button       =   document.getElementById('fb-auth');
                    userInfo     =   document.getElementById('user-info');
                    
                    if (response.authResponse) {
                        //user is already logged in and connected
                        FB.api('/me', function(info) {
                            login(response, info);
                        });
                        
                        button.onclick = function() {
                            FB.logout(function(response) {
                                logout(response);
                            });
                        };
                    } else {
                        //user is not connected to your app or logged out
                        button.innerHTML = 'Login';
                        button.onclick = function() {
                            showLoader(true);
                            FB.login(function(response) {
                                if (response.authResponse) {
                                    FB.api('/me', function(info) {
                                        login(response, info);
                                    });	   
                                } else {
                                    //user cancelled login or did not grant authorization
                                    showLoader(false);
                                }
                            }, {scope:'user_photos,status_update,publish_stream,user_about_me'});  	
                        }
                    }
                }
                
                // run once with current status and whenever the status changes
                FB.getLoginStatus(updateButton);
                FB.Event.subscribe('auth.statusChange', updateButton);	
            };
            (function() {
                var e = document.createElement('script'); e.async = true;
                e.src = document.location.protocol 
                    + '//connect.facebook.net/en_US/all.js';
                document.getElementById('fb-root').appendChild(e);
            }());
            
            // Login script. This function is called after a login call is made and fills results
            function login(response, info){
                if (response.authResponse) {
                    accessToken                                    =   response.authResponse.accessToken;
                    
                    userInfo.innerHTML                             = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
                                                                     + "<br /> Your Access Token: " + accessToken;
                    button.innerHTML                               = 'Logout';
                    showLoader(false);
                    document.getElementById('other').style.display = "block";
					
					//alert(accessToken); (works)
					if(!gotPhotos) {
						//getAlbumPhotos();
						getAlbums();
						gotPhotos = true;
					}
                }
            }
			// Being called after a logout call, clears login information and changes flags
            function logout(response){
                userInfo.innerHTML                             =   "";
                document.getElementById('debug').innerHTML     =   "";
                document.getElementById('other').style.display =   "none";
                showLoader(false);
				gotPhotos = false;
            }
			
			//Get Album data
			// This is being called once a user is logged in. It gets all album information uploaded by the user
			//Facebook uses pagination, so for any other Album that does not included in the first JSON object, 
			//we use the "next" url and call getAlbumsFromURL() with it
			function getAlbums(){
				FB.api('/me/albums?access_token='+accessToken,  function(response) {
					//var ul = document.getElementById('albums');
					var album_buttons_tag = document.getElementById("album_buttons");
					for (var i=0, l=response.data.length; i<l; i++){
						var albumid = response.data[i].id;
						//getPhotos(albumid);
						album_buttons_tag.innerHTML += '<a href="#" onclick="getPhotos('+albumid+')" id='+albumid+'></a>';
						//album_buttons_tag.innerHTML += '<img name="Album:' + albumid + '">'+albumid+'</button><br />'
						getPhotoForAlbum(albumid,response.data[i].cover_photo);
					}
					
					if(response.paging && response.paging.next) {
						var nextUrl = response.paging.next.replace('https://graph.facebook.com','');
						nextUrl = nextUrl.replace('http://graph.facebook.com','');
						getAlbumPhotosFromUrl(nextUrl);
					}
				});
			}
			
			// Gets a list of Album JSON object from a specific URL. To be called after an Album call is made and there is a next result for pagination.
			function getAlbumsFromUrl(fromUrl){
				FB.api(fromUrl,  function(response) {
					//var ul = document.getElementById('albums');
					var album_buttons_tag = document.getElementById("album_buttons");
					for (var i=0, l=response.data.length; i<l; i++){
						var albumid = response.data[i].id;
						//getPhotos(albumid);
						album_buttons_tag.innerHTML += '<a href="#" onclick="getPhotos('+albumid+')" id='+albumid+'></a>';
						//album_buttons_tag.innerHTML += '<button name="Album:' + albumid + '">'+albumid+'</button><br />'
						getPhotoForAlbum(albumid,response.data[i].cover_photo);
					}
					if(response.paging && response.paging.next) {
						var nextUrl = response.paging.next.replace('https://graph.facebook.com','');
						nextUrl = nextUrl.replace('http://graph.facebook.com','');
						getAlbumPhotosNext(nextUrl);
					}
				});
			}
			
			// This function gets the cover photo of an album from facebook (for a given id) and creates a link on the page with the picture and related URL
			function getPhotoForAlbum(albumid, photoid) {
				FB.api('/'+photoid+'?access_token='+accessToken,function(response){
					
					//Find the album from the links and change its html
					var album_button = document.getElementById(albumid);
					album_button.innerHTML = '<img src="'+response.images[response.images.length-3].source+'" />';
				});
			}
			
			// This function gets the photos of a specific album, and lists them in the HTML
			//For any other Facebook photo that does not fit in the first JSON object, Facebook use pagination to get the next results.
			//When that happens, we will call getPhotosFromURL() to request a specific set of photos (with the "next" url).
			function getPhotos(albumid) {
				
				FB.api('/'+albumid+'/photos?access_token='+accessToken,function(response){
					var photos = response.data;
					var imgs_tag = document.getElementById("images");
					//document.getElementById("photos_header").innerHTML = "Photos("+photos.length+")";
					//alert('AlbumId: ' + albumid);
					imgs_tag.innerHTML = "Click on an image to import it into Cloud Shuffle Puzzle:<br />";
					for(var v=0;v<photos.length;v++) {
						imgs_tag.innerHTML += '<a href="/facebook?img-url=' + photos[v].source + '"><img src=' + photos[v].images[photos[v].images.length-1].source + ' /></a>'
					}
					
					if(response.paging && response.paging.next) {
						var nextUrl = response.paging.next.replace('https://graph.facebook.com','');
						nextUrl = nextUrl.replace('http://graph.facebook.com','');
						getPhotosFromUrl(nextUrl);
					}
				});
			}
			
			// While getting the photos of an album, to be used wile pagination.
			function getPhotosFromUrl(fromUrl) {
				
				FB.api(fromUrl,function(response){
					var photos = response.data;
					var imgs_tag = document.getElementById("images");
					//document.getElementById("photos_header").innerHTML = "Photos("+photos.length+")";
					//alert('AlbumId: ' + albumid);
					for(var v=0;v<photos.length;v++) {
						imgs_tag.innerHTML += '<a href="/facebook?img-url=' + photos[v].source + '"><img src=' + photos[v].images[photos[v].images.length-1].source + ' /></a>'
					}
					
					if(response.paging && response.paging.next) {
						var nextUrl = response.paging.next.replace('https://graph.facebook.com','');
						nextUrl = nextUrl.replace('http://graph.facebook.com','');
						getPhotosFromUrl(nextUrl);
					}
				});
			}

            //stream publish method
            function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
                showLoader(true);
                FB.ui(
                {
                    method: 'stream.publish',
                    message: '',
                    attachment: {
                        name: name,
                        caption: '',
                        description: (description),
                        href: hrefLink
                    },
                    action_links: [
                        { text: hrefTitle, href: hrefLink }
                    ],
                    user_prompt_message: userPrompt
                },
                function(response) {
                    showLoader(false);
                });

            }
            function showStream(){
                FB.api('/me', function(response) {
                    //console.log(response.id);
                    streamPublish(response.name, 'Test: http://www.semihenergin.com/', 'hrefTitle', 'http://www.semihenergin.com/', "Share site");
                });
            }

			// Old and unused function
            function share(){
                showLoader(true);
                var share = {
                    method: 'stream.share',
                    u: 'http://www.semihenergin.com/'
                };

                FB.ui(share, function(response) { 
                    showLoader(false);
                    console.log(response); 
                });
            }
			
			// Old and unused function
            function graphStreamPublish(){
                showLoader(true);
                
                FB.api('/me/feed', 'post', 
                    { 
                        message     : "Test",
                        link        : 'http://www.semihenergin.com/',
                        picture     : '',
                        name        : 'Test',
                        description : 'Facebook Test'
                        
                }, 
                function(response) {
                    showLoader(false);
                    
                    if (!response || response.error) {
                        alert('Error occured');
                    } else {
                        alert('Post ID: ' + response.id);
                    }
                });
            }
			
			// Old and unused function
            function fqlQuery(){
                showLoader(true);
                
                FB.api('/me', function(response) {
                    showLoader(false);
                    
                    //http://developers.facebook.com/docs/reference/fql/user/
                    var query       =  FB.Data.query('select name, profile_url, sex, pic_small from user where uid={0}', response.id);
                    query.wait(function(rows) {
                       document.getElementById('debug').innerHTML =  
                         'FQL Information: '+  "<br />" + 
                         'Your name: '      +  rows[0].name                                                            + "<br />" +
                         'Your Sex: '       +  (rows[0].sex!= undefined ? rows[0].sex : "")                            + "<br />" +
                         'Your Profile: '   +  "<a href='" + rows[0].profile_url + "'>" + rows[0].profile_url + "</a>" + "<br />" +
                         '<img src="'       +  rows[0].pic_small + '" alt="" />' + "<br />";
                     });
                });
            }
			
			// Old and unused function
            function setStatus(){
                showLoader(true);
                
                status1 = document.getElementById('status').value;
                FB.api(
                  {
                    method: 'status.set',
                    status: status1
                  },
                  function(response) {
                    if (response == 0){
                        alert('Your facebook status not updated. Give Status Update Permission.');
                    }
                    else{
                        alert('Your facebook status updated');
                    }
                    showLoader(false);
                  }
                );
            }
            
			// Old and unused function
            function showLoader(status){
                if (status)
                    document.getElementById('loader').style.display = 'block';
                else
                    document.getElementById('loader').style.display = 'none';
            }
            
        </script>
		
		<button id="fb-auth" class='fun_button'>Login</button>        
        
		<div id="album_buttons">Click on an album to see its pictures:<br /></div><br /><br />
		<div id="images">Click on an image to import it into Cloud Shuffle Puzzle:<br /></div>
		
		<div id="loader" style="display:none" class="invisible">
            <img src="ajax-loader.gif" alt="loading" />
        </div>
        <br />
        <div id="user-info" class="invisible"></div>
        <br />
        <div id="debug" class="invisible"></div>
        <br />
		<div id="albums" class="invisible"></div>
		
        <div id="other" style="display:none" class="invisible">
            <a href="#" onclick="showStream(); return false;">Publish Wall Post</a> |
            <a href="#" onclick="share(); return false;">Share With Your Friends</a> |
            <a href="#" onclick="graphStreamPublish(); return false;">Publish Stream Using Graph API</a> |
            <a href="#" onclick="fqlQuery(); return false;">FQL Query Example</a>
            
            <br />
            <textarea id="status" cols="50" rows="5">Write your status here and click 'Status Set Using Legacy Api Call'</textarea>
            <br />
            <a href="#" onclick="setStatus(); return false;">Status Set Using Legacy Api Call</a>
        </div>
        </div><!-- content -->
    </body>
</html>